/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { SourceFile } from 'ts-morph';

/**
 * Import analyzer utility class
 * Responsible for analyzing import statements in source files
 */
export class ImportAnalyzer {
  /**
   * Analyze import statements in source files
   * @param sourceFile Source file
   * @returns Module import map, key is a module path, value is an array of imported identifiers
   */
  static analyzeImports(sourceFile: SourceFile): Map<string, string[]> {
    const importMap = new Map<string, string[]>();

    sourceFile.getImportDeclarations().forEach((importDeclaration) => {
      const moduleSpecifier = importDeclaration.getModuleSpecifierValue();
      const namedImports = importDeclaration.getNamedImports().map((namedImport) => namedImport.getName());
      const defaultImport = importDeclaration.getDefaultImport()?.getText();
      const namespaceImport = importDeclaration.getNamespaceImport()?.getText();
      const importNames: string[] = [];

      if (namedImports.length > 0) {
        importNames.push(...namedImports);
      }

      if (defaultImport) {
        importNames.push(defaultImport);
      }

      if (namespaceImport) {
        importNames.push(namespaceImport);
      }

      if (importNames.length > 0) {
        // Check if the module has already been imported
        if (importMap.has(moduleSpecifier)) {
          // Merge import names instead of overwriting
          const existingImports = importMap.get(moduleSpecifier)!;
          importMap.set(moduleSpecifier, [...new Set([...existingImports, ...importNames])]);
        } else {
          importMap.set(moduleSpecifier, importNames);
        }
      }
    });

    return importMap;
  }
}
